--[[
/*
 * Copyright (c) 2012 OptiCare Systems Ltd
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * Authors: Kevin Martin (kev82@khn.org.uk)
 */
]]
local function Authenticate(URL, Username, APIKey)
	local connect = require("curleasy").connector()
	local rp = require("_rackspace-cf_ResponseParser")

	connect:url(URL)
	connect:headers({
	 ["X-Auth-User"]=tostring(Username),
	 ["X-Auth-Key"]=tostring(APIKey)})
	connect:options({addheaders=1})

	local response = connect()

	if not rp.responseOK(response) then
		error("Failed to obtain new auth token")
	end

	--headers is now the output headers
	headers = rp.getResponseHeaders(response)

	if headers["X-Storage-Url"] == nil then
		error("Reply lacked storage URL")
	end
	if headers["X-Auth-Token"] == nil then
		error("Reply lacked Auth Token")
	end

	return headers["X-Storage-Url"], headers["X-Auth-Token"]
end

--Read in the information
local authserver = "https://lon.auth.api.rackspacecloud.com/v1.0"
io.write(string.format("Auth server: %s\n", authserver))
io.write(string.format("Enter username: "))
local authuser = io.read()
io.write(string.format("Auth Key: "))
local authkey = io.read()

--Authenticate initially
local storage_url, authtoken = Authenticate(authserver, authuser, authkey)

--create a worker
local gearman = require("gearman")
local worker = gearman.worker()

--This creates the gearman return value
local function returnstring()
	return string.format("return {StorageURL=\"%s\", AuthToken=\"%s\"}",
	 storage_url, authtoken)
end

--returns the current auth details
gearman.addworkfunc(worker, "rackspace_cf_authdetails", function()
 return returnstring() end)

--forces a re-authentication
gearman.addworkfunc(worker, "rackspace_cf_forceauth", function()
 storage_url, authtoken = Authenticate(authserver, authuser, authkey)
 return returnstring() end)

--starts the worker
worker()
